package com.lzb.musicplayer.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.basic.dialog.PermissionExplainDialog;
import com.lzb.musicplayer.BaseNoModelFragment;
import com.lzb.musicplayer.HomeActivity;
import com.lzb.musicplayer.R;
import com.lzb.musicplayer.activity.AlbumInfoActivity;
import com.lzb.musicplayer.activity.RecentAddActivity;
import com.lzb.musicplayer.activity.RecordActivity;
import com.lzb.musicplayer.activity.SelAudioActivity;
import com.lzb.musicplayer.activity.SettingActivity;
import com.lzb.musicplayer.adapter.AlbumAdapter;
import com.lzb.musicplayer.adapter.ArtistAdapter;
import com.lzb.musicplayer.bean.GroupMusicInfo;
import com.lzb.musicplayer.bean.MusicFile;
import com.lzb.musicplayer.databinding.FragmentHomeBinding;
import com.lzb.musicplayer.utils.MusicScanner;
import com.lzb.musicplayer.utils.MusicScannerUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> implements View.OnClickListener, OnItemClickListener {

    private List<MusicFile> listAll = new ArrayList<>();
    private ArtistAdapter artistAdapter;
    private AlbumAdapter albumAdapter;

    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSetting.setOnClickListener(this);
        mDataBinding.llRecord.setOnClickListener(this);
        mDataBinding.llRecentAdd.setOnClickListener(this);
        mDataBinding.llRingtoneEdit.setOnClickListener(this);
        mDataBinding.llRandomPlay.setOnClickListener(this);
        mDataBinding.llGetPermission.setOnClickListener(this);

        mDataBinding.rvArtistList.setLayoutManager(new GridLayoutManager(mContext, 3));
        artistAdapter = new ArtistAdapter();
        mDataBinding.rvArtistList.setAdapter(artistAdapter);
        artistAdapter.setOnItemClickListener(this);

        mDataBinding.rvAlbumList.setLayoutManager(new GridLayoutManager(mContext, 3));
        albumAdapter = new AlbumAdapter();
        mDataBinding.rvAlbumList.setAdapter(albumAdapter);
        albumAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivSetting) {//设置
            startActivity(SettingActivity.class);
        } else if (id == R.id.llRecord) {//历史记录
            startActivity(RecordActivity.class);
        } else if (id == R.id.llRecentAdd) {//最近添加
            startActivity(RecentAddActivity.class);
        } else if (id == R.id.llRingtoneEdit) {//铃声编辑
            startActivity(SelAudioActivity.class);
        } else if (id == R.id.llRandomPlay) {//随机播放
            if (listAll == null || listAll.size() == 0) return;
            HomeActivity activity = (HomeActivity) getActivity();
            activity.setRandomMusicList(listAll);
        } else if (id == R.id.llGetPermission) {//申请权限
            getPermission();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        GroupMusicInfo groupMusicInfo = albumAdapter.getData().get(position);
        List<MusicFile> list = groupMusicInfo.getList();
        Intent intent = new Intent(getActivity(), AlbumInfoActivity.class);
        intent.putExtra("list", (Serializable) list);
        startActivity(intent);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        boolean hasPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_MEDIA_AUDIO)
                    == PackageManager.PERMISSION_GRANTED;
        } else {
            hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED;
        }
        if (hasPermission) {
            getPermission();
            mDataBinding.llGetPermission.setVisibility(View.GONE);
            mDataBinding.llData.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.llGetPermission.setVisibility(View.VISIBLE);
            mDataBinding.llData.setVisibility(View.GONE);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            boolean hasPermission;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_MEDIA_AUDIO)
                        == PackageManager.PERMISSION_GRANTED;
            } else {
                hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_GRANTED;
            }
            if (hasPermission) {
                getPermission();
                mDataBinding.llGetPermission.setVisibility(View.GONE);
                mDataBinding.llData.setVisibility(View.VISIBLE);
            } else {
                mDataBinding.llGetPermission.setVisibility(View.VISIBLE);
                mDataBinding.llData.setVisibility(View.GONE);
            }
        }
    }

    private void getPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_audio_permission));
        List<String> permissionsInManifest = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissionsInManifest.add(Manifest.permission.READ_MEDIA_AUDIO);
        } else {
            permissionsInManifest.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            permissionsInManifest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        PermissionUtils.permission(permissionsInManifest.toArray(new String[permissionsInManifest.size()])).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                getData();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    private void getData() {
        showDialog(getString(R.string.loading));
        listAll.clear();
        new MusicScannerUtil().loadMusicFiles(getActivity(), new MusicScannerUtil.OnCallBackListener() {
            @Override
            public void onCallBack(List<MusicFile> list) {
                dismissDialog();
                if (list != null && list.size() > 0) {
                    listAll.addAll(list);
                    setArtistList(list);
                    setAlbumList(list);
                } else {
                    mDataBinding.rvArtistList.setVisibility(View.GONE);
                    mDataBinding.rvAlbumList.setVisibility(View.GONE);
                    mDataBinding.tvArtistNoData.setVisibility(View.VISIBLE);
                    mDataBinding.tvAlbumNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    public void setArtistList(List<MusicFile> files) {
        List<GroupMusicInfo> groupedList = MusicScanner.groupByProperty(files, MusicFile::getArtist);

        // 筛选包含最近7天歌曲的艺术家
        List<GroupMusicInfo> filteredList = new ArrayList<>();
        if (groupedList != null) {
            long now = TimeUtils.getNowMills();
            long sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000L;

            for (GroupMusicInfo group : groupedList) {
                List<MusicFile> musicFiles = group.getList();
                if (musicFiles != null) {
                    for (MusicFile musicFile : musicFiles) {
                        long fileModifiedTime = FileUtils.getFileLastModified(musicFile.getPath());
                        if (fileModifiedTime >= sevenDaysAgo) {
                            filteredList.add(group);
                            break; // 只要有一个歌曲符合条件就添加该艺术家
                        }
                    }
                }
            }
        }

        if (filteredList.size() > 0) {
            artistAdapter.setList(filteredList);
            mDataBinding.rvArtistList.setVisibility(View.VISIBLE);
            mDataBinding.tvArtistNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvArtistList.setVisibility(View.GONE);
            mDataBinding.tvArtistNoData.setVisibility(View.VISIBLE);
        }
    }

    public void setAlbumList(List<MusicFile> files) {
        List<GroupMusicInfo> groupedList = MusicScanner.groupByProperty(files, MusicFile::getAlbum);

        // 筛选包含最近7天歌曲的专辑
        List<GroupMusicInfo> filteredList = new ArrayList<>();
        if (groupedList != null) {
            long now = TimeUtils.getNowMills();
            long sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000L;

            for (GroupMusicInfo group : groupedList) {
                List<MusicFile> musicFiles = group.getList();
                if (musicFiles != null) {
                    for (MusicFile musicFile : musicFiles) {
                        long fileModifiedTime = FileUtils.getFileLastModified(musicFile.getPath());
                        if (fileModifiedTime >= sevenDaysAgo) {
                            filteredList.add(group);
                            break; // 只要有一个歌曲符合条件就添加该专辑
                        }
                    }
                }
            }
        }

        if (filteredList.size() > 0) {
            albumAdapter.setList(filteredList);
            mDataBinding.rvAlbumList.setVisibility(View.VISIBLE);
            mDataBinding.tvAlbumNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvAlbumList.setVisibility(View.GONE);
            mDataBinding.tvAlbumNoData.setVisibility(View.VISIBLE);
        }
    }
}